package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.dto.MemberDetailUpdateDTO;
import com.ruoyi.system.dto.MemberListDTO;
import com.ruoyi.system.dto.MemberShipDTO;
import com.ruoyi.system.enumeration.TicketTypeEnum;
import com.ruoyi.system.service.*;
import com.ruoyi.system.util.AbdulEmptyUtils;
import com.ruoyi.system.util.BookingNumberGenerator;
import com.ruoyi.system.util.DateUtils;
import com.ruoyi.system.util.StoreIdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MembershipManagementServiceImpl implements MembershipManagementService {

    @Autowired
    private IMemberOverviewService memberOverview;

    @Autowired
    private ISyRechargeInfoService rechargeInfoService;


    @Autowired
    private ISyTicketDurationCardService cardService;


    @Autowired
    private IMemberListService memberListService;

    @Autowired
    private IMemberStoredValueCardService storedValueCardService;

    @Autowired
    private StoreIdUtils storeIdUtils;

    @Autowired
    private IStoreSettingsService storeSettingsService;

    @Autowired
    private MembershipDurationCardService durationCardService;

    @Autowired
    private IMembershipVoucherService membershipVoucherService;

    @Autowired
    private IMemberLevelService memberLevelService;


    @Override
    public MembershipManagementVO listOverview(MemberShipDTO memberShipDTO) {
        MembershipManagementVO vo = new MembershipManagementVO();
        //会员概览
        if (AbdulEmptyUtils.isEmpty(memberShipDTO.getStartTime()) || AbdulEmptyUtils.isEmpty(memberShipDTO.getEndTime())) {
            throw new RuntimeException("开始时间和结束时间不能为空");
        }
        LambdaQueryWrapper<MemberOverview> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(MemberOverview::getStoreId, storeIdUtils.getStoreId());
        wrapper.between(MemberOverview::getCreateTime, DateUtils.getStartOfDay(memberShipDTO.getEndTime()), DateUtils.getEndOfDay(memberShipDTO.getEndTime()));
        wrapper.orderByDesc(MemberOverview::getCreateTime);
        wrapper.last("limit 1");
        MemberOverview member = memberOverview.getOne(wrapper);
        if (!AbdulEmptyUtils.isEmpty(member)) {
            vo.setTotalMembers(member.getTotalMembers());
            vo.setNewMembers(member.getNewMembers());
            vo.setCommonMembers(member.getRegularMembers());
            vo.setStopMembers(member.getInactiveMembers());
            vo.setRegularMembers(member.getActiveMembers());
            vo.setBackendCreated(member.getBackendCreated());
            vo.setSelfServiceCreated(member.getSelfServiceCreated());
            vo.setGoldMembers(member.getGoldMembersWithDiscount());
        }
        //会员收入
        membershipIncome(vo, memberShipDTO);
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(MemberList memberList) {
        if (AbdulEmptyUtils.isEmpty(memberList.getMemberName())) {
            throw new RuntimeException("会员姓名不能为空");
        }
        if (AbdulEmptyUtils.isEmpty(memberList.getPhone())) {
            throw new RuntimeException("会员手机号码不能为空");
        }
        if (AbdulEmptyUtils.isEmpty(memberList.getMemberLevelId())) {
            throw new RuntimeException("会员等级不能为空");
        }
        String phone = memberList.getPhone();
        String lastFourDigits = phone.length() >= 4 ? phone.substring(phone.length() - 4) : phone;
        memberList.setMemberCardNo(BookingNumberGenerator.generateBookingNumber() + lastFourDigits);

        //  会员创建完成之后新增一条储值卡记录
        Long storeId = storeIdUtils.getStoreId();
        StoreSettings byId = storeSettingsService.getById(storeId);
        if (AbdulEmptyUtils.isEmpty(byId)) {
            throw new RuntimeException("请先完善店铺信息");
        }
        memberList.setRegisterStore(byId.getStoreName());
        memberList.setStoreId(storeId);
        return memberListService.save(memberList);
        // todo 创建会员成功之后 暂不新增储值卡
//        MemberStoredValueCard card = new MemberStoredValueCard();
//        card.setCardName("储值卡-" + lastFourDigits);
//        card.setCardType(1);
//        card.setCardNumber(BookingNumberGenerator.generateBookingNumber() + lastFourDigits);
//        card.setMemberPhone(memberList.getPhone());
//        card.setBalance(new BigDecimal(0));
//        card.setGiftBalance(new BigDecimal(0));
//        card.setExpiryDate(null);
//        card.setStatus(1);
//        card.setStoreName(byId.getStoreName());
//        card.setStoreId(storeId);
//        card.setMemberId(Long.valueOf(memberList.getId()));
//         storedValueCardService.save(card);
    }

    @Override
    public IPage<MemberList> memberList(MemberListDTO memberShipDTO) {
        LambdaQueryWrapper<MemberList> wrapper = Wrappers.lambdaQuery();
        // 按会员姓名查询
        if (!AbdulEmptyUtils.isEmpty(memberShipDTO.getMemberName())) {
            wrapper.eq(MemberList::getMemberName, memberShipDTO.getMemberName());
        }
        // 按手机号码查询
        if (!AbdulEmptyUtils.isEmpty(memberShipDTO.getPhone())) {
            wrapper.eq(MemberList::getPhone, memberShipDTO.getPhone());
        }
        // 按会员卡号查询
        if (!AbdulEmptyUtils.isEmpty(memberShipDTO.getMemberCardNo())) {
            wrapper.eq(MemberList::getMemberCardNo, memberShipDTO.getMemberCardNo());
        }
        // 按会员等级查询
        if (!AbdulEmptyUtils.isEmpty(memberShipDTO.getMemberLevelId())) {
            wrapper.eq(MemberList::getMemberLevelId, memberShipDTO.getMemberLevelId());
        }
        // 按会员状态查询
        if (!AbdulEmptyUtils.isEmpty(memberShipDTO.getMemberStatus())) {
            wrapper.eq(MemberList::getMemberStatus, memberShipDTO.getMemberStatus());
        }
        // 按性别查询
        if (!AbdulEmptyUtils.isEmpty(memberShipDTO.getGender())) {
            wrapper.eq(MemberList::getGender, memberShipDTO.getGender());
        }
        // 按推荐会员ID查询
        if (memberShipDTO.getReferrerId() != null) {
            wrapper.eq(MemberList::getReferrerId, memberShipDTO.getReferrerId());
        }
        // 按注册门店名称查询
        if (!AbdulEmptyUtils.isEmpty(memberShipDTO.getRegisterStore())) {
            wrapper.like(MemberList::getRegisterStore, memberShipDTO.getRegisterStore());
        }
        // 按操作员工姓名模糊查询
        if (!AbdulEmptyUtils.isEmpty(memberShipDTO.getOperatorStaff())) {
            wrapper.like(MemberList::getOperatorStaff, memberShipDTO.getOperatorStaff());
        }
        // 按过期时间范围查询
        if (memberShipDTO.getExpirationStartTime() != null && memberShipDTO.getExpirationEndTime() != null) {
            wrapper.between(MemberList::getExpirationDate, memberShipDTO.getExpirationStartTime(), memberShipDTO.getExpirationEndTime());
        } else if (memberShipDTO.getExpirationStartTime() != null) {
            wrapper.ge(MemberList::getExpirationDate, memberShipDTO.getExpirationStartTime());
        } else if (memberShipDTO.getExpirationEndTime() != null) {
            wrapper.le(MemberList::getExpirationDate, memberShipDTO.getExpirationEndTime());
        }
        // 按创建时间范围查询
        if (memberShipDTO.getCreateStartTime() != null && memberShipDTO.getCreateEndTime() != null) {
            wrapper.between(MemberList::getCreateTime, memberShipDTO.getCreateStartTime(), memberShipDTO.getCreateEndTime());
        } else if (memberShipDTO.getCreateStartTime() != null) {
            wrapper.ge(MemberList::getCreateTime, memberShipDTO.getCreateStartTime());
        } else if (memberShipDTO.getCreateEndTime() != null) {
            wrapper.le(MemberList::getCreateTime, memberShipDTO.getCreateEndTime());
        }
        // 按出生日期范围查询
        if (memberShipDTO.getBirthdayStartTime() != null && memberShipDTO.getBirthdayEndTime() != null) {
            wrapper.between(MemberList::getDateBirth, memberShipDTO.getBirthdayStartTime(), memberShipDTO.getBirthdayEndTime());
        } else if (memberShipDTO.getBirthdayStartTime() != null) {
            wrapper.ge(MemberList::getDateBirth, memberShipDTO.getBirthdayStartTime());
        } else if (memberShipDTO.getBirthdayEndTime() != null) {
            wrapper.le(MemberList::getDateBirth, memberShipDTO.getBirthdayEndTime());
        }

//        // 按累计消费金额范围查询
//        if (memberShipDTO.getTotalConsumeStartAmount() != null && memberShipDTO.getTotalConsumeEndAmount() != null) {
//            wrapper.between(MemberList::getTotalBalance, memberShipDTO.getTotalConsumeStartAmount(), memberShipDTO.getTotalConsumeEndAmount());
//        } else if (memberShipDTO.getTotalConsumeStartAmount() != null) {
//            wrapper.ge(MemberList::getTotalBalance, memberShipDTO.getTotalConsumeStartAmount());
//        } else if (memberShipDTO.getTotalConsumeEndAmount() != null) {
//            wrapper.le(MemberList::getTotalBalance, memberShipDTO.getTotalConsumeEndAmount());
//        }
//
//        // 按最近未消费天数查询
//        if (memberShipDTO.getLastUnconsumedDays() != null) {
//            Date lastActiveTime = DateUtils.addDaysToDate(new Date(), -memberShipDTO.getLastUnconsumedDays());
//            wrapper.le(MemberList::getUpdateTime, lastActiveTime);
//        }
        wrapper.eq(MemberList::getStoreId, storeIdUtils.getStoreId());
        wrapper.eq(MemberList::getIsDelete, 0);
        wrapper.orderByDesc(MemberList::getUpdateTime);
        IPage<MemberList> list = memberListService.page(new Page<>(memberShipDTO.getPageNum(), memberShipDTO.getPageSize()), wrapper); //会员列表

        //统计各个会员的 桌台时长卡(张)	桌台次卡(张)	商品次卡(张)	代金券(张)数量
        if (!AbdulEmptyUtils.isEmpty(list.getRecords())) {
            //翻译推举会员的名字
            Set<Long> referredIds = list.getRecords().stream().map(MemberList::getReferrerId).collect(Collectors.toSet());
            if (!AbdulEmptyUtils.isEmpty(referredIds)) {
                LambdaQueryWrapper<MemberList> lambdaQueryWrapper = Wrappers.lambdaQuery();
                lambdaQueryWrapper.in(MemberList::getId, referredIds);
                List<MemberList> memberList = memberListService.list(lambdaQueryWrapper);
                if (!AbdulEmptyUtils.isEmpty(memberList)) {
                    Map<Long, String> idToNameMap = memberList.stream()
                            .collect(Collectors.toMap(
                                    MemberList::getId,       // Key: id
                                    MemberList::getMemberName // Value: memberName
                            ));
                    for (MemberList record : list.getRecords()) {
                        record.setReferrerIdDesc(idToNameMap.get(record.getReferrerId()));
                    }
                }
            }

            List<Long> memberIdList = list.getRecords().stream()
                    .map(MemberList::getId)
                    .collect(Collectors.toList());
            //门店id
            Long currentStoreId = storeIdUtils.getStoreId();

            // 批量查询储值卡数量
            LambdaQueryWrapper<MemberStoredValueCard> storedValueWrapper = Wrappers.lambdaQuery();
            storedValueWrapper.in(MemberStoredValueCard::getMemberId, memberIdList);
            storedValueWrapper.eq(MemberStoredValueCard::getStoreId, currentStoreId);
            List<MemberStoredValueCard> storedValueCards = storedValueCardService.list(storedValueWrapper);

            Map<Long, Long> storedValueCountMap = storedValueCards.stream()
                    .collect(Collectors.groupingBy(MemberStoredValueCard::getMemberId, Collectors.counting()));

            // 批量查询时长卡/次卡/商品卡数量
            LambdaQueryWrapper<MembershipDurationCard> durationWrapper = Wrappers.lambdaQuery();
            durationWrapper.in(MembershipDurationCard::getMemberId, memberIdList);
            durationWrapper.eq(MembershipDurationCard::getStoreId, currentStoreId);
            List<MembershipDurationCard> durationCards = durationCardService.list(durationWrapper);

            Map<Long, int[]> cardTypeCountMap = new HashMap<>();
            Optional.ofNullable(durationCards).ifPresent(cards -> {
                cards.forEach(card -> {
                    if (card == null || card.getIsType() == null) return;
                    Long memberId = card.getMemberId();
                    int[] counts = cardTypeCountMap.computeIfAbsent(memberId, k -> new int[]{0, 0, 0});

                    switch (card.getIsType()) {
                        case 1:
                            counts[0]++;
                            break;
                        case 2:
                            counts[1]++;
                            break;
                        case 3:
                            counts[2]++;
                            break;
                        default:
                            System.err.println("Unknown isType value: " + card.getIsType());
                            break;
                    }

                    cardTypeCountMap.put(memberId, counts);
                });
            });

            // 批量查询代金券数量
            LambdaQueryWrapper<MembershipVoucher> voucherWrapper = Wrappers.lambdaQuery();
            voucherWrapper.in(MembershipVoucher::getMemberId, memberIdList);
            voucherWrapper.eq(MembershipVoucher::getStoreId, currentStoreId);
            List<MembershipVoucher> vouchers = membershipVoucherService.list(voucherWrapper);

            Map<String, Long> voucherCountMap = vouchers.stream()
                    .collect(Collectors.groupingBy(MembershipVoucher::getMemberId, Collectors.counting()));

            // 设置结果
            list.getRecords().forEach(item -> {
                Long id = item.getId();
                item.setStoredValueCard(storedValueCountMap.getOrDefault(id, 0L).intValue());

                int[] counts = cardTypeCountMap.getOrDefault(id, new int[]{0, 0, 0});
                item.setTableDurationCard(counts[0]);
                item.setTableSingleCard(counts[1]);
                item.setProductSingleCard(counts[2]);

                item.setCoupon(voucherCountMap.getOrDefault(id.toString(), 0L).intValue());
            });
        }
        return list;
    }

    /**
     * 会员详情
     *
     * @param id 会员id
     * @return
     */
    @Override
    public memberDetailVO memberDetail(Long id) {
        //构建返回体
        memberDetailVO memberDetailVO = new memberDetailVO();
        if (AbdulEmptyUtils.isEmpty(id)) {
            return memberDetailVO;
        }

        LambdaQueryWrapper<MemberList> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(MemberList::getId, id);
        MemberList serviceOne = memberListService.getOne(wrapper);
        if (AbdulEmptyUtils.isEmpty(serviceOne)) {
            return memberDetailVO;
        }
        if (!AbdulEmptyUtils.isEmpty(serviceOne.getReferrerId())) {
            serviceOne.setReferrerIdDesc(memberListService.getById(serviceOne.getReferrerId()).getMemberName());
        }
        //查询注册门店名称
        StoreSettings store = storeIdUtils.getStore(serviceOne.getStoreId());
        if (!AbdulEmptyUtils.isEmpty(store)) {
            serviceOne.setCreateStore(store.getStoreName());
        }
        // 查询储值卡数量
        LambdaQueryWrapper<MemberStoredValueCard> storedValueWrapper = Wrappers.lambdaQuery();
        storedValueWrapper.eq(MemberStoredValueCard::getMemberId, serviceOne.getId());
        storedValueWrapper.eq(MemberStoredValueCard::getStoreId, serviceOne.getStoreId());
        Integer count = Math.toIntExact(storedValueCardService.count(storedValueWrapper));
        serviceOne.setStoredValueCard(count);
        // 查询时长卡/次卡/商品卡数量
        LambdaQueryWrapper<MembershipDurationCard> durationWrapper = Wrappers.lambdaQuery();
        durationWrapper.eq(MembershipDurationCard::getMemberId, serviceOne.getId());
        durationWrapper.eq(MembershipDurationCard::getStoreId, serviceOne.getStoreId());
        List<MembershipDurationCard> durationCards = durationCardService.list(durationWrapper);
        if (CollectionUtils.isNotEmpty(durationCards)) {
            long count1 = durationCards.stream().filter(e -> e.getIsType().equals(1)).count();
            serviceOne.setTableDurationCard(Math.toIntExact(count1));
            long count2 = durationCards.stream().filter(e -> e.getIsType().equals(2)).count();
            serviceOne.setTableSingleCard(Math.toIntExact(count2));
            long count3 = durationCards.stream().filter(e -> e.getIsType().equals(3)).count();
            serviceOne.setProductSingleCard(Math.toIntExact(count3));
        }
        // 查询代金券数量
        LambdaQueryWrapper<MembershipVoucher> voucherWrapper = Wrappers.lambdaQuery();
        voucherWrapper.eq(MembershipVoucher::getMemberId, serviceOne.getId());
        voucherWrapper.eq(MembershipVoucher::getStoreId, serviceOne.getStoreId());
        long count1 = membershipVoucherService.count(voucherWrapper);
        serviceOne.setCoupon((int) count1);

        //消费信息 TODO
        memberConsumeVO memberConsumeVO = new memberConsumeVO();


        //微信绑定信息 TODO
        memberWechatVO memberWechatVO = new memberWechatVO();


        //会员权益
        LambdaQueryWrapper<MemberLevel> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(MemberLevel::getId, serviceOne.getMemberLevelId());
        MemberLevel memberLevel = memberLevelService.getOne(lambdaQuery);

        memberDetailVO.setMemberList(serviceOne);
        memberDetailVO.setMemberWechatVO(memberWechatVO);
        memberDetailVO.setMemberConsumeVO(memberConsumeVO);
        memberDetailVO.setMemberPrivilegeVO(memberLevel);
        return memberDetailVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateMemberList(MemberDetailUpdateDTO memberList) {
        if (AbdulEmptyUtils.isEmpty(memberList.getId())) {
            throw new RuntimeException("会员id不能为空");
        }
        MemberList member = memberListService.getById(memberList.getId());
        if (AbdulEmptyUtils.isEmpty(member)) {
            throw new RuntimeException("会员不存在");
        }
        if (memberList.getOperationType().equals(1)) {
            if (AbdulEmptyUtils.isEmpty(memberList.getAvailablePoints())) {
                throw new RuntimeException("增加积分不能为空");
            }
            //增加积分
            if (memberList.getAvailablePoints() > 0) {
                member.setAvailablePoints(member.getAvailablePoints() + memberList.getAvailablePoints());
                member.setTotalAvailablePoints(member.getTotalAvailablePoints() == null ? 0 : member.getTotalAvailablePoints() + memberList.getAvailablePoints());
            }
        } else if (memberList.getOperationType() == 2) {
            if (AbdulEmptyUtils.isEmpty(memberList.getAvailablePoints())) {
                throw new RuntimeException("扣除积分不能为空");
            }
            if (member.getAvailablePoints() < memberList.getAvailablePoints()) {
                throw new RuntimeException("会员积分不足");
            }
            member.setAvailablePoints(member.getAvailablePoints() - memberList.getAvailablePoints());
        } else if (memberList.getOperationType() == 3) {
            basicMessage(member, memberList);
        } else if (memberList.getOperationType() == 4) {
            if (member.getMemberStatus() == 1) {
                member.setMemberStatus(2);
            } else if (member.getMemberStatus() == 2) {
                member.setMemberStatus(1);
            }
        } else if (memberList.getOperationType() == 5) {
            if (AbdulEmptyUtils.isEmpty(memberList.getIsBlacklist())) {
                throw new RuntimeException("请选择是否拉黑");
            }
            member.setIsBlacklist(memberList.getIsBlacklist());
        } else if (memberList.getOperationType() == 6) {
            member.setIsDelete(1);
        } else if (memberList.getOperationType() == 7) {
            if (AbdulEmptyUtils.isEmpty(memberList.getAuthMethod())) {
                throw new RuntimeException("请选择验证方式");
            }
            if (memberList.getAuthMethod().equals("PASSWORD")) {
                if (!AbdulEmptyUtils.isEmpty(memberList.getPassword()) && !AbdulEmptyUtils.isEmpty(memberList.getConfirmPassword())) {
                    if (!memberList.getPassword().equals(memberList.getConfirmPassword())) {
                        throw new RuntimeException("密码不一致");
                    }
                    member.setPassword(memberList.getPassword());
                }
            }
        }
        return memberListService.updateById(member);
    }

    public void basicMessage(MemberList member, MemberDetailUpdateDTO memberList) {
        if (!AbdulEmptyUtils.isEmpty(memberList.getMemberName())) {
            member.setMemberName(memberList.getMemberName());
        }
        if (!AbdulEmptyUtils.isEmpty(memberList.getPhone())) {
            member.setPhone(memberList.getPhone());
        }
        if (!AbdulEmptyUtils.isEmpty(memberList.getMemberCardNo())) {
            if (!member.getMemberCardNo().equals(memberList.getMemberCardNo())) {
                LambdaQueryWrapper<MemberList> wrapper = Wrappers.lambdaQuery();
                wrapper.eq(MemberList::getMemberCardNo, memberList.getMemberCardNo());
                MemberList serviceOne = memberListService.getOne(wrapper);
                if (!AbdulEmptyUtils.isEmpty(serviceOne)) {
                    throw new RuntimeException("修改失败,会员卡号已存在");
                }
            }
            member.setMemberCardNo(memberList.getMemberCardNo());
        }
        if (!AbdulEmptyUtils.isEmpty(memberList.getDateBirth())) {
            member.setDateBirth(memberList.getDateBirth());
        }
        if (!AbdulEmptyUtils.isEmpty(memberList.getGender())) {
            member.setGender(memberList.getGender());
        }
        if (!AbdulEmptyUtils.isEmpty(memberList.getExpirationDate())) {
            member.setExpirationDate(memberList.getExpirationDate());
        }
        if (!AbdulEmptyUtils.isEmpty(memberList.getAddress())) {
            member.setAddress(memberList.getAddress());
        }
        if (!AbdulEmptyUtils.isEmpty(memberList.getRemark())) {
            member.setRemark(memberList.getRemark());
        }
        if (!AbdulEmptyUtils.isEmpty(memberList.getReferrerId())) {
            member.setReferrerId(memberList.getReferrerId());
        }
        if (!AbdulEmptyUtils.isEmpty(memberList.getMemberLevelId())) {
            member.setMemberLevelId(memberList.getMemberLevelId());
        }
    }


    //会员收入
    public void membershipIncome(MembershipManagementVO vo, MemberShipDTO memberShipDTO) {
        //储值卡 /定额储值卡
        LambdaQueryWrapper<SyRechargeInfo> wrapper = Wrappers.lambdaQuery();

        wrapper.between(SyRechargeInfo::getCreateTime, memberShipDTO.getStartTime(), memberShipDTO.getEndTime());
        wrapper.orderByDesc(SyRechargeInfo::getCreateTime);
        List<SyRechargeInfo> rechargeInfos = rechargeInfoService.list(wrapper);
        if (!AbdulEmptyUtils.isEmpty(rechargeInfos)) {
            //储值卡充值金额
            BigDecimal totalRechargeValue = rechargeInfos.stream()
                    .filter(e -> e.getIsType().equals(1))
                    .map(e -> new BigDecimal(e.getRechargeAmount().toString()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            vo.setStoredCardRecharge(totalRechargeValue);
            //储值卡退款金额
            BigDecimal totalRefund = rechargeInfos.stream()
                    .filter(e -> e.getIsType().equals(1))
                    .map(e -> new BigDecimal(e.getCancelRefund().toString()).add(new BigDecimal(e.getManualRefund().toString())))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            vo.setStoredCardRefund(totalRefund);
            // 储值卡列表对象
            ISyRechargeInfoVO syRechargeInfoVO = new ISyRechargeInfoVO();
            List<SyRechargeInfo> syRechargeInfoList = rechargeInfos.stream().filter(e -> e.getIsType().equals(1)).collect(Collectors.toList());
            if (!AbdulEmptyUtils.isEmpty(syRechargeInfoList)) {
                BigDecimal rechargeAmount = syRechargeInfoList.stream().map(e -> new BigDecimal(e.getRechargeAmount().toString())).reduce(BigDecimal.ZERO, BigDecimal::add);
                syRechargeInfoVO.setRechargeAmount(rechargeAmount);
                BigDecimal cancelRefund = syRechargeInfoList.stream().map(e -> new BigDecimal(e.getCancelRefund().toString())).reduce(BigDecimal.ZERO, BigDecimal::add);
                syRechargeInfoVO.setCancelRefund(cancelRefund);
                BigDecimal manualRefund = syRechargeInfoList.stream().map(e -> new BigDecimal(e.getManualRefund().toString())).reduce(BigDecimal.ZERO, BigDecimal::add);
                syRechargeInfoVO.setManualRefund(manualRefund);
                BigDecimal actualRecharge = syRechargeInfoList.stream().map(e -> new BigDecimal(e.getActualRecharge().toString())).reduce(BigDecimal.ZERO, BigDecimal::add);
                syRechargeInfoVO.setActualRecharge(actualRecharge);
            }
            syRechargeInfoVO.setRechargeInfos(syRechargeInfoList);
            vo.setSyRechargeInfoVO(syRechargeInfoVO);
            //定额储值卡金额
            BigDecimal reduce = rechargeInfos.stream()
                    .filter(e -> e.getIsType().equals(2))
                    .map(e -> new BigDecimal(e.getRechargeAmount().toString()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            vo.setFixedStoredCard(reduce);
            //定额储值卡退款金额
            BigDecimal reduce1 = rechargeInfos.stream()
                    .filter(e -> e.getIsType().equals(2))
                    .map(e -> new BigDecimal(e.getCancelRefund().toString()).add(new BigDecimal(e.getManualRefund().toString())))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            vo.setFixedStoredCardRefund(reduce1);
            //定额储值卡列表对象
            ISyRechargeInfoVO requalSyRechargeInfoVO = new ISyRechargeInfoVO();
            List<SyRechargeInfo> requalSyRechargeInfoList = rechargeInfos.stream().filter(e -> e.getIsType().equals(2)).collect(Collectors.toList());
            if (!AbdulEmptyUtils.isEmpty(requalSyRechargeInfoList)) {
                BigDecimal rechargeAmount = requalSyRechargeInfoList.stream().map(e -> new BigDecimal(e.getRechargeAmount().toString())).reduce(BigDecimal.ZERO, BigDecimal::add);
                requalSyRechargeInfoVO.setRechargeAmount(rechargeAmount);
                BigDecimal cancelRefund = requalSyRechargeInfoList.stream().map(e -> new BigDecimal(e.getCancelRefund().toString())).reduce(BigDecimal.ZERO, BigDecimal::add);
                requalSyRechargeInfoVO.setCancelRefund(cancelRefund);
                BigDecimal manualRefund = requalSyRechargeInfoList.stream().map(e -> new BigDecimal(e.getManualRefund().toString())).reduce(BigDecimal.ZERO, BigDecimal::add);
                requalSyRechargeInfoVO.setManualRefund(manualRefund);
                BigDecimal actualRecharge = requalSyRechargeInfoList.stream().map(e -> new BigDecimal(e.getActualRecharge().toString())).reduce(BigDecimal.ZERO, BigDecimal::add);
                requalSyRechargeInfoVO.setActualRecharge(actualRecharge);

            }
            requalSyRechargeInfoVO.setRechargeInfos(requalSyRechargeInfoList);
            vo.setSyRechargeInfoVO(requalSyRechargeInfoVO);
        }
        //桌台时长卡 桌台次卡 商品次卡 代金券 会员收入
        LambdaQueryWrapper<SyTicketDurationCard> lambdaed = Wrappers.lambdaQuery();
        lambdaed.between(SyTicketDurationCard::getCreateTime, memberShipDTO.getStartTime(), memberShipDTO.getEndTime());
        List<SyTicketDurationCard> list = cardService.list(lambdaed);
        if (!AbdulEmptyUtils.isEmpty(list)) {
            //桌台时长卡
            vo.setTableTimeCard(getTotalRechargeValue(list, TicketTypeEnum.TABLE_DURATION_CARD.getValue()));
            vo.setTableTimeCardRefund(getTotalRefundValue(list, TicketTypeEnum.TABLE_DURATION_CARD.getValue()));

            //桌台次卡金额
            vo.setTableCountCard(getTotalRechargeValue(list, TicketTypeEnum.TABLE_VISIT_CARD.getValue()));
            vo.setTableCountCardRefund(getTotalRefundValue(list, TicketTypeEnum.TABLE_VISIT_CARD.getValue()));

            //商品次卡
            vo.setProductCountCard(getTotalRechargeValue(list, TicketTypeEnum.PRODUCT_VISIT_CARD.getValue()));
            vo.setProductCountCardRefund(getTotalRefundValue(list, TicketTypeEnum.PRODUCT_VISIT_CARD.getValue()));
            //代金券金额
            vo.setVoucher(getTotalRechargeValue(list, TicketTypeEnum.VOUCHER.getValue()));
            vo.setVoucherRefund(getTotalRefundValue(list, TicketTypeEnum.VOUCHER.getValue()));
        }

        //桌台时长卡对象列表
        SyTicketDurationCardVO syTicketDurationCardVO = new SyTicketDurationCardVO();
        syTicketDurationCardVO.setSyTicketDurationCards(list(list, TicketTypeEnum.TABLE_DURATION_CARD.getValue()));
        syTicketDurationCardVO.setActualIncome(getTotalRecharge(list, TicketTypeEnum.TABLE_DURATION_CARD.getValue()));
        syTicketDurationCardVO.setRefundAmount(getTotalRefund(list, TicketTypeEnum.TABLE_DURATION_CARD.getValue()));
        syTicketDurationCardVO.setSalesAmount(syTicketDurationCardVO.getActualIncome().add(syTicketDurationCardVO.getRefundAmount()));
        vo.setSyTicketDurationCardVO(syTicketDurationCardVO);
        //桌台次卡
        SyTicketDurationCardVO syTicketCountCards = new SyTicketDurationCardVO();
        syTicketCountCards.setSyTicketDurationCards(list(list, TicketTypeEnum.TABLE_VISIT_CARD.getValue()));
        syTicketCountCards.setActualIncome(getTotalRecharge(list, TicketTypeEnum.TABLE_VISIT_CARD.getValue()));
        syTicketCountCards.setRefundAmount(getTotalRefund(list, TicketTypeEnum.TABLE_VISIT_CARD.getValue()));
        syTicketCountCards.setSalesAmount(syTicketCountCards.getActualIncome().add(syTicketCountCards.getRefundAmount()));
        vo.setSyTicketCountCards(syTicketCountCards);

        //商品次卡
        SyTicketDurationCardVO syProductCountCards = new SyTicketDurationCardVO();
        syProductCountCards.setSyTicketDurationCards(list(list, TicketTypeEnum.PRODUCT_VISIT_CARD.getValue()));
        syProductCountCards.setActualIncome(getTotalRecharge(list, TicketTypeEnum.PRODUCT_VISIT_CARD.getValue()));
        syProductCountCards.setRefundAmount(getTotalRefund(list, TicketTypeEnum.PRODUCT_VISIT_CARD.getValue()));
        syProductCountCards.setSalesAmount(syProductCountCards.getActualIncome().add(syProductCountCards.getRefundAmount()));
        vo.setSyProductCountCards(syProductCountCards);
        //代金券
        SyTicketDurationCardVO syVouchers = new SyTicketDurationCardVO();
        syVouchers.setSyTicketDurationCards(list(list, TicketTypeEnum.VOUCHER.getValue()));
        syVouchers.setActualIncome(getTotalRecharge(list, TicketTypeEnum.VOUCHER.getValue()));
        syVouchers.setRefundAmount(getTotalRefund(list, TicketTypeEnum.VOUCHER.getValue()));
        syVouchers.setSalesAmount(syVouchers.getActualIncome().add(syVouchers.getRefundAmount()));
        vo.setSyVouchers(syVouchers);
    }

    /**
     * 获取0-桌台时长卡 1-桌台次卡 2-商品次卡 3-代金券的会员收入
     *
     * @param list
     * @param type
     * @return
     */
    public BigDecimal getTotalRechargeValue(List<SyTicketDurationCard> list, Integer type) {
        return list.stream()
                .filter(e -> e.getIsType().equals(type))
                .map(e -> new BigDecimal(e.getActualIncome().toString()))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    /**
     * 获取0-桌台时长卡 1-桌台次卡 2-商品次卡 3-代金券的会员退款
     *
     * @param list
     * @param type
     * @return
     */
    public BigDecimal getTotalRefundValue(List<SyTicketDurationCard> list, Integer type) {
        return list.stream()
                .filter(e -> e.getIsType().equals(type))
                .map(e -> new BigDecimal(e.getRefundAmount().toString()))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    /**
     * 获取0-桌台时长卡 1-桌台次卡 2-商品次卡 3-代金券对象列表
     *
     * @param list
     * @param type
     * @return
     */
    public List<SyTicketDurationCard> list(List<SyTicketDurationCard> list, Integer type) {
        return list.stream()
                .filter(e -> e.getIsType().equals(type))
                .collect(Collectors.toList());

    }

    /**
     * 实际收入
     */
    public BigDecimal getTotalRecharge(List<SyTicketDurationCard> list, Integer type) {
        return list.stream()
                .filter(e -> e.getIsType().equals(type))
                .map(e -> new BigDecimal(e.getActualIncome().toString()))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    /**
     * 退款金额
     */
    public BigDecimal getTotalRefund(List<SyTicketDurationCard> list, Integer type) {
        return list.stream()
                .filter(e -> e.getIsType().equals(type))
                .map(e -> new BigDecimal(e.getRefundAmount().toString()))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

}
